// ==UserScript==
// @name         自动学习脚本
// @namespace    https://zhycarge.github.io
// @author       ZHYCarge
// @version      1.1.0
// @description  自动进行学习
// @match        https://ldxf.enorth.com.cn/main.jsp
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @grant        GM_notification
// @updateURL    https://gitee.com/zhycarge/soft_renew/raw/master/codes/auto_study.js
// @downloadURL  https://gitee.com/zhycarge/soft_renew/raw/master/codes/auto_study.js
// ==/UserScript==

(function () {
    'use strict';
    // 配置存储
    const CONFIG = {
        userId: GM_getValue('userId', ''),
        tips: GM_getValue('tips', ''),
        lastUpdate: GM_getValue('lastUpdate', '')
    };
    // 状态变量
    const STATE = {
        isRunning: false,
        taskQueue: [],
        intervals: [],
        currentTask: null
    };
    // DOM元素ID常量
    const ELEMENT_IDS = {
        controlPanel: 'studyControlPanel',
        countdown: 'studyCountdown',
        settingsDialog: 'studySettingsDialog',
        taskList: 'studyTaskList'
    };
    // 创建主控制面板
    function createControlPanel() {
        // 如果已存在则先移除
        const existingPanel = document.getElementById(ELEMENT_IDS.controlPanel);
        if (existingPanel) existingPanel.remove();
        const panel = document.createElement('div');
        panel.id = ELEMENT_IDS.controlPanel;
        Object.assign(panel.style, {
            position: 'fixed',
            left: '10px',
            bottom: '10px',
            zIndex: '9999',
            background: 'rgba(255,255,255,0.95)',
            border: '1px solid #ddd',
            padding: '15px',
            fontSize: '14px',
            boxShadow: '0 2px 10px rgba(0,0,0,0.15)',
            borderRadius: '8px',
            display: 'flex',
            flexDirection: 'column',
            gap: '12px',
            minWidth: '220px'
        });
        // 标题
        const title = document.createElement('div');
        title.textContent = '自动学习控制台';
        title.style.fontWeight = 'bold';
        title.style.borderBottom = '1px solid #eee';
        title.style.paddingBottom = '8px';
        panel.appendChild(title);
        // 按钮容器
        const btnContainer = document.createElement('div');
        btnContainer.style.display = 'flex';
        btnContainer.style.gap = '8px';
        btnContainer.style.flexWrap = 'wrap';
        // 开始按钮
        const startBtn = document.createElement('button');
        startBtn.textContent = '▶ 开始';
        startBtn.onclick = startLearning;
        Object.assign(startBtn.style, {
            padding: '6px 12px',
            background: '#4CAF50',
            color: 'white',
            border: 'none',
            borderRadius: '4px'
        });
        // 停止按钮
        const stopBtn = document.createElement('button');
        stopBtn.textContent = '■ 停止';
        stopBtn.onclick = stopLearning;
        Object.assign(stopBtn.style, {
            padding: '6px 12px',
            background: '#f44336',
            color: 'white',
            border: 'none',
            borderRadius: '4px'
        });
        // 设置按钮
        const settingsBtn = document.createElement('button');
        settingsBtn.textContent = '⚙ 设置';
        settingsBtn.onclick = showSettingsDialog;
        Object.assign(settingsBtn.style, {
            padding: '6px 12px',
            background: '#2196F3',
            color: 'white',
            border: 'none',
            borderRadius: '4px'
        });
        btnContainer.appendChild(startBtn);
        btnContainer.appendChild(stopBtn);
        btnContainer.appendChild(settingsBtn);
        panel.appendChild(btnContainer);
        // 状态显示
        const statusContainer = document.createElement('div');
        statusContainer.style.display = 'flex';
        statusContainer.style.flexDirection = 'column';
        statusContainer.style.gap = '6px';
        // 倒计时显示
        const countdown = document.createElement('div');
        countdown.id = ELEMENT_IDS.countdown;
        countdown.textContent = '准备就绪';
        countdown.style.fontSize = '13px';
        countdown.style.color = '#666';
        statusContainer.appendChild(countdown);
        // 当前任务显示
        const currentTaskDisplay = document.createElement('div');
        currentTaskDisplay.id = 'currentTaskDisplay';
        currentTaskDisplay.textContent = '未开始任务';
        currentTaskDisplay.style.fontSize = '13px';
        currentTaskDisplay.style.color = '#333';
        statusContainer.appendChild(currentTaskDisplay);
        panel.appendChild(statusContainer);
        document.body.appendChild(panel);
    }
    // 显示设置对话框
    function showSettingsDialog() {
        // 移除现有对话框
        const existingDialog = document.getElementById(ELEMENT_IDS.settingsDialog);
        if (existingDialog) existingDialog.remove();
        const dialog = document.createElement('div');
        dialog.id = ELEMENT_IDS.settingsDialog;
        Object.assign(dialog.style, {
            position: 'fixed',
            left: '50%',
            top: '50%',
            transform: 'translate(-50%, -50%)',
            zIndex: '10000',
            background: 'white',
            border: '1px solid #ddd',
            padding: '20px',
            boxShadow: '0 4px 20px rgba(0,0,0,0.15)',
            borderRadius: '8px',
            width: '320px',
            maxWidth: '90vw'
        });
        // 标题和关闭按钮
        const header = document.createElement('div');
        header.style.display = 'flex';
        header.style.justifyContent = 'space-between';
        header.style.alignItems = 'center';
        header.style.marginBottom = '15px';
        const title = document.createElement('h3');
        title.textContent = '学习参数设置';
        title.style.margin = '0';
        const closeBtn = document.createElement('button');
        closeBtn.textContent = '×';
        closeBtn.onclick = () => dialog.remove();
        Object.assign(closeBtn.style, {
            background: 'none',
            border: 'none',
            fontSize: '20px',
            cursor: 'pointer',
            padding: '0 8px'
        });
        header.appendChild(title);
        header.appendChild(closeBtn);
        dialog.appendChild(header);
        // 表单容器
        const form = document.createElement('div');
        form.style.display = 'flex';
        form.style.flexDirection = 'column';
        form.style.gap = '15px';
        // 用户ID输入
        const userIdGroup = document.createElement('div');
        const userIdLabel = document.createElement('label');
        userIdLabel.textContent = '用户ID:';
        userIdLabel.style.display = 'block';
        userIdLabel.style.marginBottom = '5px';
        userIdLabel.style.fontWeight = '500';
        const userIdInput = document.createElement('input');
        userIdInput.type = 'number';
        userIdInput.value = CONFIG.userId;
        Object.assign(userIdInput.style, {
            width: '100%',
            padding: '8px',
            border: '1px solid #ddd',
            borderRadius: '4px',
            boxSizing: 'border-box'
        });
        userIdInput.placeholder = '请输入用户ID';
        userIdGroup.appendChild(userIdLabel);
        userIdGroup.appendChild(userIdInput);
        form.appendChild(userIdGroup);
        // 访问标签输入
        const tipsGroup = document.createElement('div');
        const tipsLabel = document.createElement('label');
        tipsLabel.textContent = '访问Tips:';
        tipsLabel.style.display = 'block';
        tipsLabel.style.marginBottom = '5px';
        tipsLabel.style.fontWeight = '500';
        const tipsInput = document.createElement('input');
        tipsInput.type = 'text';
        tipsInput.value = CONFIG.tips;
        Object.assign(tipsInput.style, {
            width: '100%',
            padding: '8px',
            border: '1px solid #ddd',
            borderRadius: '4px',
            boxSizing: 'border-box'
        });
        tipsInput.placeholder = '请输入访问Tips';
        tipsGroup.appendChild(tipsLabel);
        tipsGroup.appendChild(tipsInput);
        form.appendChild(tipsGroup);
        // 帮助文本
        const helpText = document.createElement('div');
        helpText.textContent = '提示：这些参数请从页面源代码中查找';
        helpText.style.fontSize = '12px';
        helpText.style.color = '#666';
        helpText.style.marginTop = '-10px';
        form.appendChild(helpText);
        // 按钮容器
        const btnContainer = document.createElement('div');
        btnContainer.style.display = 'flex';
        btnContainer.style.justifyContent = 'flex-end';
        btnContainer.style.gap = '10px';
        btnContainer.style.marginTop = '10px';
        // 取消按钮
        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = '取消';
        cancelBtn.onclick = () => dialog.remove();
        Object.assign(cancelBtn.style, {
            padding: '8px 16px',
            background: '#f5f5f5',
            border: '1px solid #ddd',
            borderRadius: '4px',
            cursor: 'pointer'
        });
        // 保存按钮
        const saveBtn = document.createElement('button');
        saveBtn.textContent = '保存设置';
        saveBtn.onclick = () => {
            const newUserId = userIdInput.value.trim();
            const newTips = tipsInput.value.trim();
            if (!newUserId || !newTips) {
                alert('用户ID和访问标签不能为空！');
                return;
            }
            CONFIG.userId = newUserId;
            CONFIG.tips = newTips;
            CONFIG.lastUpdate = new Date().toLocaleString();
            GM_setValue('userId', CONFIG.userId);
            GM_setValue('tips', CONFIG.tips);
            GM_setValue('lastUpdate', CONFIG.lastUpdate);
            dialog.remove();
            showNotification('参数已保存', '配置已成功更新');
        };
        Object.assign(saveBtn.style, {
            padding: '8px 16px',
            background: '#4CAF50',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer'
        });
        btnContainer.appendChild(cancelBtn);
        btnContainer.appendChild(saveBtn);
        form.appendChild(btnContainer);
        dialog.appendChild(form);
        document.body.appendChild(dialog);
    }
    // 显示通知
    function showNotification(title, message) {
        if (typeof GM_notification !== 'undefined') {
            GM_notification({
                title: title,
                text: message,
                timeout: 3000
            });
        } else {
            alert(`${title}\n${message}`);
        }
    }
    // 更新状态显示
    function updateStatus(message, isError = false) {
        const el = document.getElementById(ELEMENT_IDS.countdown);
        if (el) {
            el.textContent = message;
            el.style.color = isError ? '#f44336' : '#666';
        }
    }
    // 更新当前任务显示
    function updateCurrentTask(taskName) {
        const el = document.getElementById('currentTaskDisplay');
        if (el) {
            el.textContent = taskName ? `当前任务: ${taskName}` : '无进行中任务';
        }
    }
    // 解析学习时长
    function parseDuration(durationText) {
        // 支持多种格式： "45分钟"、"45"、"45min" 等
        const match = durationText.match(/(\d+)/);
        return match ? parseInt(match[1], 10) : 0;
    }
    // 从iframe提取学习任务
    async function extractTasksFromIframe() {
        const iframe = document.getElementById('content');
        if (!iframe) {
            updateStatus('错误: 未找到学习内容iframe', true);
            return [];
        }
        // 等待iframe加载完成
        await new Promise(resolve => {
            if (iframe.contentDocument.readyState === 'complete') {
                resolve();
            } else {
                iframe.onload = resolve;
            }
        });
        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        // 增强的tips获取逻辑
        let tipsPage = '';
        const tipsSelectors = [
            '#tips',
            'input[name="tips"]',
            '[name="tips"]',
            'input#tips',
            'input[type="hidden"][name="tips"]'
        ];
        for (const selector of tipsSelectors) {
            const element = iframeDoc.querySelector(selector);
            if (element) {
                tipsPage = element.value || element.getAttribute('value') || element.textContent || '';
                if (tipsPage) break;
            }
        }
        if (!tipsPage) {
            updateStatus('错误: 无法获取页面验证标签', true);
            return [];
        }
        if (CONFIG.tips && tipsPage !== CONFIG.tips) {
            updateStatus('错误: 页面验证标签不匹配', true);
            showNotification('安全警告', '页面验证标签与保存的不一致！');
            return [];
        }
        // 提取学习任务
        const tasks = [];
        const rows = iframeDoc.querySelectorAll('#learnStateTab #sort tr');
        rows.forEach(row => {
            const cols = row.querySelectorAll('td');
            if (cols.length < 5) return;
            const name = cols[1].textContent.trim();
            const durationText = cols[2].textContent.trim();
            const status = cols[3].textContent.trim();
            const button = cols[4].querySelector('button[onclick]');
            if (status.includes('未学') && button) {
                const onclickText = button.getAttribute('onclick');
                // 增强的studyId提取
                let studyId = '';
                const idPatterns = [
                    /study\(['"]?([^'")]+)['"]?\)/,
                    /chapterId=([^&]+)/,
                    /id=([^&]+)/,
                    /(\d{3,})/
                ];
                for (const pattern of idPatterns) {
                    const match = onclickText.match(pattern);
                    if (match && match[1]) {
                        studyId = match[1];
                        break;
                    }
                }
                if (studyId) {
                    tasks.push({
                        name,
                        duration: parseDuration(durationText),
                        id: studyId,
                        rawDuration: durationText
                    });
                } else {
                    console.warn('无法提取studyId:', onclickText);
                }
            }
        });
        return tasks;
    }
    // 倒计时器
    async function countdownTimer(seconds, taskName) {
        return new Promise(resolve => {
            updateCurrentTask(taskName);
            let remaining = seconds;
            updateStatus(`剩余时间: ${formatTime(remaining)}`);
            const interval = setInterval(() => {
                remaining--;
                if (remaining <= 0 || !STATE.isRunning) {
                    clearInterval(interval);
                    STATE.intervals = STATE.intervals.filter(i => i !== interval);
                    resolve();
                } else {
                    updateStatus(`剩余时间: ${formatTime(remaining)}`);
                }
            }, 1000);
            STATE.intervals.push(interval);
        });
    }
    // 格式化时间显示
    function formatTime(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    // 开始学习流程
    async function startLearning() {
        if (STATE.isRunning) return;
        // 验证配置
        if (!CONFIG.userId || !CONFIG.tips) {
            updateStatus('错误: 请先设置用户参数', true);
            showSettingsDialog();
            return;
        }
        STATE.isRunning = true;
        updateStatus('正在准备学习任务...');
        try {
            STATE.taskQueue = await extractTasksFromIframe();
            if (STATE.taskQueue.length === 0) {
                updateStatus('没有可用的学习任务', true);
                STATE.isRunning = false;
                return;
            }
            updateStatus(`找到 ${STATE.taskQueue.length} 个学习任务`);
            // 执行任务队列
            for (const task of STATE.taskQueue) {
                if (!STATE.isRunning) break;
                STATE.currentTask = task;
                updateStatus(`开始学习: ${task.name}`);

                const studyUrl = `https://ldxf.enorth.com.cn/learnstate/LearnStateAction!startStudy.do?svo.chapterId=${task.id}&svo.userId=${CONFIG.userId}&questionBankId=479&levelId=694&tips=${CONFIG.tips}`;
                const iframe = document.getElementById('content');
                if (iframe) {
                    iframe.src = studyUrl;
                    // 等待iframe加载
                    await new Promise(resolve => {
                        iframe.onload = resolve;
                    });
                }
                // 随机增加10-30秒的额外时间
                const totalSeconds = (task.duration * 60) + Math.floor(Math.random() * 21) + 10;
                await countdownTimer(totalSeconds, task.name);
                if (STATE.isRunning) {
                    updateStatus(`完成: ${task.name}`);
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
            }
            if (STATE.isRunning) {
                updateStatus('所有学习任务已完成');
                showNotification('学习完成', '所有任务已执行完毕');
            } else {
                updateStatus('学习已手动停止');
            }
        } catch (error) {
            console.error('学习过程中出错:', error);
            updateStatus(`错误: ${error.message}`, true);
        } finally {
            STATE.isRunning = false;
            STATE.currentTask = null;
            updateCurrentTask(null);
        }
    }
    // 停止学习
    function stopLearning() {
        STATE.isRunning = false;
        STATE.taskQueue = [];
        STATE.currentTask = null;
        // 清除所有计时器
        STATE.intervals.forEach(interval => clearInterval(interval));
        STATE.intervals = [];
        updateStatus('学习已停止');
        updateCurrentTask(null);
    }

    // 初始化
    function init() {
        createControlPanel();

        // 注册Tampermonkey菜单命令
        if (typeof GM_registerMenuCommand !== 'undefined') {
            GM_registerMenuCommand("打开设置面板", showSettingsDialog);
            GM_registerMenuCommand("开始学习", startLearning);
            GM_registerMenuCommand("停止学习", stopLearning);
        }

        // 如果缺少配置，显示设置对话框
        if (!CONFIG.userId || !CONFIG.tips) {
            setTimeout(() => {
                showSettingsDialog();
                updateStatus('请先设置学习参数', true);
            }, 1500);
        }
    }
    // 页面加载完成后初始化
    window.addEventListener('load', init);
})();